/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.aeo.bll;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Collections;

/**
 * @author Frederic Branczyk & Robert Piwonski
 */
public class Export {

    // begin of attributes
    private ArrayList<Student> students;
    private ArrayList<Subject> subjects;
    private Manager m;
    // end of attributes


    // begin of methods
    // Constructor
    /**
     * Exports the relevant program data into an CSV-Table
     * @param subjectsAlreadyExisting Subject to be saved
     * @param studentsAlreadyExisting Students to be saved
     * @param m Manager object that contains all data
     */
    public Export(ArrayList<Subject> subjectsAlreadyExisting, ArrayList<Student> studentsAlreadyExisting, Manager m){
        this.students = studentsAlreadyExisting;
        this.subjects = subjectsAlreadyExisting;
        this.m = m;
    }

    /**
     * Asks user where to save data and does so.
     * @param file File to save into
     * @throws MalformedURLException 
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void exportData(File file) throws MalformedURLException, FileNotFoundException, IOException {
        OutputStreamWriter writer;
        if(file.getName().contains(".csv")){ // Has the user remembered adding the correct file extension ?
            writer = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("ISO-8859-1"));  
        } 
        else{    // If not, add it for him.           
            writer = new OutputStreamWriter(new FileOutputStream(new File(file.getAbsolutePath() + ".csv")), Charset.forName("ISO-8859-1"));
        }
        String sep = System.getProperty("line.separator"); // Might vary between Windows, Mac or Linux, so ask for the system-dependent line seperator. 
        // Start writing the subjects, first.
        // Give a head line for orientation.
        writer.append("//Subject title;Abbreviation;Minimum participants;Maximum participants;" + sep);
        for (Subject su : this.subjects) {
            writer.append(su.getName()+";" + su.getAbbreviation() + su.getPeriodAbbreviation() + ";" + su.getMinStudents()+";" + su.getMaxStudents() + sep);
        }
        // Then continue saving the students' data.
        // Give a seperator line for orientation.
        writer.append("//First name;Last name;School class;Subject 1;Subject 2;Subject 3;Subject 4;Subject 5;Subject 6" + sep);
        for (Student st : this.students) {
            writer.append(st.getFirstname());
            writer.append(";");
            writer.append(st.getLastname());
            writer.append(";");
            writer.append(st.getcClass());
            writer.append(";");
            Subject[] studentsSubjects = st.getSubjectList();                
            for(int i = 0; i < studentsSubjects.length; i++){
                if(studentsSubjects[i] != null){
                    writer.append(studentsSubjects[i].getAbbreviation() + studentsSubjects[i].getPeriodAbbreviation());
                    if(i < studentsSubjects.length-1 ){ // Not the last element in the line
                        writer.append(";");   
                    }
                }else {
                    writer.append(";");
                }
            }
            writer.append(sep); // Next line
        }
        writer.flush();
        writer.close();
    }
    
    /**
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void exportAllCourses() throws FileNotFoundException, IOException {
        for(int i=0; i<this.m.getSchedule().size(); i++) {
            ArrayList<Course> list1 = this.m.getSchedule().get(i);
            for(Course c:list1) {
                this.exportCourse(c, i+1);
            }
        }
    }
    
    /**
     * Exports all students that did not get their wishes fulfilled.
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void exportImpossibleStudents() throws FileNotFoundException, IOException {
        File f = new File("./data/impossibleStudents.csv");
        ArrayList<Student> list = new ArrayList<Student>();
        for(Student s:this.students) {
            if(s.getState()==2) {
                list.add(s);
            }
        }
        OutputStreamWriter writer;
        String sep = System.getProperty("line.separator"); // Might vary between Windows, Mac or Linux, so ask for the system-dependent line seperator.
        writer = new OutputStreamWriter(new FileOutputStream(f), Charset.forName("ISO-8859-1"));
        // Start writing the subjects, first.
        // Give a head line for orientation.
        writer.append(this.m.getLanguage().getString("lastname"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("firstname"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("class"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 1");
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 2");
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 3");
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 4");
        writer.append(sep);
        Collections.sort(list);
        for (Student s : list) {
            writer.append(s.getLastname() + ";" + s.getFirstname() + ";" + s.getcClass() + ";");
            if(s.getCourseList()[0]!=null)
                writer.append(s.getCourseList()[0].getName()+" ("+s.getCourseList()[0].getSubject().getAbbreviation()+s.getCourseList()[0].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            writer.append(";");
            if(s.getCourseList()[1]!=null)
                writer.append(s.getCourseList()[1].getName()+" ("+s.getCourseList()[1].getSubject().getAbbreviation()+s.getCourseList()[1].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            writer.append(";");
            if(s.getCourseList()[2]!=null)
                writer.append(s.getCourseList()[2].getName()+" ("+s.getCourseList()[2].getSubject().getAbbreviation()+s.getCourseList()[2].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            writer.append(";");
            if(s.getCourseList()[3]!=null)
                writer.append(s.getCourseList()[3].getName()+" ("+s.getCourseList()[3].getSubject().getAbbreviation()+s.getCourseList()[3].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            if(s.getState()==2) {
                writer.append(";");
                writer.append(this.m.getLanguage().getString("revote"));
            }
            writer.append(sep);
        }
        writer.flush();
        writer.close();
    }
    
    /**
     * Exports a certain course
     * @param c Course
     * @param layer Course's layer
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void exportCourse(Course c, int layer ) throws FileNotFoundException, IOException {
        OutputStreamWriter writer;
        File f = new File("./data/Layers/"+layer+"/"+c.getName()+" ("+c.getSubject().getAbbreviation()+c.getSubject().getPeriodAbbreviation()+").csv");
        String sep = System.getProperty("line.separator"); // Might vary between Windows, Mac or Linux, so ask for the system-dependent line seperator.
        writer = new OutputStreamWriter(new FileOutputStream(f), Charset.forName("ISO-8859-1"));
        // Start writing the subjects, first.
        // Give a head line for orientation.
        writer.append(c.getName()+" ("+c.getSubject().getAbbreviation()+c.getSubject().getPeriodAbbreviation()+")" + sep);
        writer.append(sep);
        writer.append(this.m.getLanguage().getString("firstname"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("lastname"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("class"));
        writer.append(sep);
        Collections.sort(c.getStudentList());
        for (Student s : c.getStudentList()) {
            writer.append(s.getLastname() + ";" + s.getFirstname() + ";" + s.getcClass() + sep);
        }
        writer.flush();
        writer.close();
    }
    
    /**
     * Exports all classes.
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void exportAllClasses() throws FileNotFoundException, IOException {
        ArrayList<ArrayList<Student>> allClasses = new ArrayList<ArrayList<Student>>();
        ArrayList<String> alreadyClasses = new ArrayList<String>();
        for(Student s:this.students) {
            if(!alreadyClasses.contains(s.getcClass())) {
                ArrayList<Student> temp = new ArrayList<Student>();
                temp.add(s);
                allClasses.add(temp);
                alreadyClasses.add(s.getcClass());
            }else {
                int i = alreadyClasses.indexOf(s.getcClass());
                allClasses.get(i).add(s);
            }
        }
        int j = 0;
        for(ArrayList<Student> list1:allClasses) {
            File f = new File("./data/Classes/"+alreadyClasses.get(j) +".csv");
            this.exportClass(list1, f);
            j++;
        }
    }
    
    /**
     * Exports a certain school classes
     * @param list List of all students.
     * @param file File to write into.
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void exportClass(ArrayList<Student> list, File file) throws FileNotFoundException, IOException {
        OutputStreamWriter writer;
        File f = file;
        String sep = System.getProperty("line.separator"); // Might vary between Windows, Mac or Linux, so ask for the system-dependent line seperator.
        writer = new OutputStreamWriter(new FileOutputStream(f), Charset.forName("ISO-8859-1"));
        // Start writing the subjects, first.
        // Give a head line for orientation.
        writer.append(this.m.getLanguage().getString("lastname"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("firstname"));
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 1");
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 2");
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 3");
        writer.append(";");
        writer.append(this.m.getLanguage().getString("course")+" 4");
        writer.append(sep);
        Collections.sort(list);
        for (Student s : list) {
            writer.append(s.getLastname() + ";" + s.getFirstname() + ";");
            if(s.getCourseList()[0]!=null)
                writer.append(s.getCourseList()[0].getName()+" ("+s.getCourseList()[0].getSubject().getAbbreviation()+s.getCourseList()[0].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            writer.append(";");
            if(s.getCourseList()[1]!=null)
                writer.append(s.getCourseList()[1].getName()+" ("+s.getCourseList()[1].getSubject().getAbbreviation()+s.getCourseList()[1].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            writer.append(";");
            if(s.getCourseList()[2]!=null)
                writer.append(s.getCourseList()[2].getName()+" ("+s.getCourseList()[2].getSubject().getAbbreviation()+s.getCourseList()[2].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            writer.append(";");
            if(s.getCourseList()[3]!=null)
                writer.append(s.getCourseList()[3].getName()+" ("+s.getCourseList()[3].getSubject().getAbbreviation()+s.getCourseList()[3].getSubject().getPeriodAbbreviation()+")");
            else
                writer.append(this.m.getLanguage().getString("<none>"));
            if(s.getState()==2) {
                writer.append(";");
                writer.append(this.m.getLanguage().getString("revote"));
            }
            writer.append(sep);
        }
        writer.flush();
        writer.close();
    }
    
    /**
     * Deletes directory to be overwritten.
     * @param dir Directory
     * @return
     */
    public boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }
    
    // end of methods
}